<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.title" clearable class="filter-item" style="width: 200px;" placeholder="请输入卡名称" />
      <el-input v-model="listQuery.cardNo" clearable class="filter-item" style="width: 200px;" placeholder="请输入卡号" />
      <el-select v-model="listQuery.cardUse" clearable style="width: 200px" class="filter-item" placeholder="请选择卡状态" >
        <el-option v-for="(item,index) in cardStatusMap" :key="index" :label="item.name" :value="item.value" />
      </el-select>
      <el-select v-model="listQuery.source" clearable style="width: 200px" class="filter-item" placeholder="请选择制卡方式" >
        <el-option v-for="(item,index) in sourceMap" :key="index" :label="item.name" :value="item.value" />
      </el-select>
      <el-button
        v-permission="['promote:card:query']"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >查找</el-button>
      <el-button
        v-permission="['promote:card:create']"
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >添加</el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-data-analysis"
        @click="cardHandleExport"
      >导出</el-button>
      <!-- <el-button
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >当前页导出</el-button> -->
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
      style="white-space: pre-line"
    >
      <el-table-column align="center" label="卡批次" prop="cardNo" sortable />
      <el-table-column align="center" label="卡名称" prop="title" />
      <el-table-column align="center" label="卡介绍" prop="description" />
      <el-table-column align="center" label="会员卡数量" prop="total">
        <template slot-scope="scope">{{ scope.row.total >= 0 ? scope.row.total : "不限" }}</template>
      </el-table-column>
      <el-table-column align="center" label="会员卡额度" prop="money">
        <template slot-scope="scope">{{ scope.row.money }}</template>
      </el-table-column>
      <!--<el-table-column align="center" label="剩余数量" prop="surplus">
        <template slot-scope="scope">{{ scope.row.surplus >= 0 ? scope.row.surplus : "不限" }}</template>
      </el-table-column>
      <el-table-column align="center" label="每人限领" prop="limit">
        <template slot-scope="scope">{{ scope.row.limit >= 0 ? scope.row.limit : "不限" }}</template>
      </el-table-column>-->
      <!--<el-table-column align="center" label="状态" prop="status">
        <template slot-scope="scope">
          <el-tag> {{ scope.row.status | formatStatus }} </el-tag>
        </template>
      </el-table-column>-->
      <el-table-column align="center" label="状态" prop="cardUse">
        <template slot-scope="scope">
          <el-tag> {{ scope.row.cardUse | formatUse }} </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="制卡方式" prop="source">
        <template slot-scope="scope">
          <el-tag> {{ scope.row.source | formatSource }} </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!--<el-button
            v-permission="['promote:usercard:update']"
            type="primary"
            size="mini"
            @click="handleStatus(scope.row)"
          >{{ scope.row.status | formatStatusBtn }}</el-button>-->
          <el-button
            v-permission="['promote:usercard:product']"
            v-if="scope.row.cardUse === 0 && scope.row.source ===0"
            type="primary"
            size="mini"
            @click="handleProduct(scope.row)"
          >制卡</el-button>
          <el-button
            v-if="scope.row.source === 1"
            type="primary"
            size="mini"
            @click="handleImport(scope.row)"
          >导入</el-button>
          <el-button
            v-permission="['promote:card:query']"
            type="primary"
            size="medium"
            @click="handleDetail(scope.row)"
          >绑定用户</el-button>
          <!--<el-button
            v-permission="['promote:card:update']"
            v-if="scope.row.cardUse === 0"
            type="info"
            size="mini"
            @click="handleUpdate(scope.row)"
          >编辑</el-button>-->
          <el-button
            v-permission="['promote:card:delete']"
            v-if="scope.row.cardUse === 0"
            type="danger"
            size="mini"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNo"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-input v-model="dataForm.id" type="hidden" />
        <el-form-item prop="source">
          <el-radio-group v-model="dataForm.source">
            <el-radio :label="0">手动创建</el-radio>
            <el-radio :label="1">批量导入</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="V卡名称" prop="title">
          <el-input v-model="dataForm.title" />
        </el-form-item>
        <el-form-item v-if="dataForm.source=='0'" label="V卡金额" prop="total">
          <el-input v-model="dataForm.money" >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="dataForm.source=='0'" label="V卡数量" prop="total">
          <el-input v-model="dataForm.total" >
            <template slot="append">张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="介绍" prop="description" >
          <el-input v-model="dataForm.description" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="importDialogVisible"
      title="导入用户卡"
      width="35%"
    >
      <el-dialog
        :visible.sync="innerImportDialogVisible"
        width="30%"
        title="系统提示"
        append-to-body>
        <el-row style="margin-bottom: 20px;">
          <el-col :span="4">总计:{{ allResult }}</el-col>
          <el-col :span="4">成功:{{ successResult }}</el-col>
          <el-col :span="4">失败:{{ errResult }}</el-col>
        </el-row>
        <el-row v-if="errResult && errResult > 0">
          <el-col :span="4"><el-button type="primary" @click="handleErrResult">导出错误信息</el-button></el-col>
        </el-row>
      </el-dialog>
      <div style="border:none;">
        <el-button icon="el-icon-document-copy" type="primary" size="small" style="margin-left: 15px;" @click="checkFile">选择文件</el-button>
        <span>{{ fileName }}</span>
        <el-input id="fileinput" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" type="file" style="display: none;" @change="checkFileSure"/>
        <el-link type="primary" href="../../static/excel/template.xls" target="_blank" download="导入模板.xls">下载模板</el-link>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button :disabled="(!fileName)" :loading="importOptLoading" type="primary" @click="importExcel">导 入</el-button>
        <el-input v-model="currentCardId" type="hidden" />
      </span>
    </el-dialog>
  </div>
</template>

<style>
.el-table .cell {
  white-space: pre-line;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>

<script>
import { listCard, createCard, deleteCard, activeCard, productCard, updateCard } from '@/api/card'
import { importExcel, exportUserCardToExcel } from '@/api/usercard'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
export default {
  name: 'Card',
  components: { Pagination },
  filters: {
    formatStatus(status) {
      if (status === 0) {
        return '下架'
      } else if (status === 1) {
        return '正常'
      } else if (status < 0) {
        return '已过期'
      } else {
        return '错误状态'
      }
    },
    formatUse(cardUse) {
      if (cardUse === 0) {
        return '未制卡'
      } else if (cardUse === 1) {
        return '已制卡'
      } else if (cardUse === 2) {
        return '已作废'
      } else {
        return '错误状态'
      }
    },
    formatStatusBtn(status) {
      if (status === 1) {
        return '冻结'
      } else if (status === 0) {
        return '激活'
      } else if (status < 0) {
        return '已过期'
      } else {
        return '错误状态'
      }
    },
    formatSource(source) {
      if (source === 1) {
        return '批量导入'
      } else if (source === 0) {
        return '手动创建'
      }
    }
  },
  data() {
    return {
      sourceMap: [{ value: 0, name: '手动创建' }, { value: 1, name: '批量导入' }],
      cardStatusMap: [{ value: 0, name: '未制卡' }, { value: 1, name: '已制卡' }],
      list: undefined,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        limit: 20,
        type: undefined,
        status: undefined,
        title: undefined,
        source: undefined,
        cardNo: undefined
      },
      options: [],
      dataForm: {
        id: undefined,
        title: undefined,
        type: 1,
        description: undefined,
        total: 0,
        limit: 0,
        money: 0,
        min: 0,
        status: 1,
        source: 0
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        title: [{ required: true, message: '会员卡标题不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '会员卡类型不能为空', trigger: 'blur' }],
        total: [{ required: true, message: '会员卡总量不能为空', trigger: 'blur' }, { pattern: /^[0-9]*$/, message: '请输入整数' }, { min: 1, max: 9, message: '大于1,小于1亿' }],
        money: [{ required: true, message: '会员卡金额不能为空', trigger: 'blur' }, { pattern: /^[0-9]*$/, message: '请输入整数' }, { min: 1, max: 9, message: '大于1,小于1亿' }]
      },
      downloadLoading: false,
      importDialogVisible: false,
      innerImportDialogVisible: false,
      successResult: 0,
      errResult: 0,
      allResult: 0,
      importOptLoading: false,
      uploadForm: new FormData(),
      fileName: '',
      file: '',
      currentCardId: undefined
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      listCard(this.listQuery)
        .then(response => {
          // 为过期会员卡赋负值
          response.data.data.items.forEach(item => {
            var now = new Date()
            if (item.gmtEnd < now) {
              item.status = -1
            }
            item.money = item.money / 100
          })
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        title: undefined,
        desc: undefined,
        total: 0,
        money: 0,
        min: 0,
        limit: 0,
        type: 1,
        status: 1,
        source: 0
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          // if (this.dataForm.total === undefined || this.dataForm.total === '' || parseInt(this.dataForm.total) === 0) {
          //   this.$notify.error({
          //     title: '提示',
          //     message: 'V卡数量不可以为0'
          //   })
          //   this.dialogFormVisible = true
          //   return false
          // }
          // if (this.dataForm.money === undefined || this.dataForm.money === '' || parseInt(this.dataForm.money) === 0) {
          //   this.$notify.error({
          //     title: '提示',
          //     message: 'V卡金额不可以为0'
          //   })
          //   this.dialogFormVisible = true
          //   return false
          // }
          this.dataForm.money = Math.round((this.dataForm.money * 100 + Number.EPSILON) * 100) / 100
          createCard(this.dataForm)
            .then(response => {
              this.getList()
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '创建卡成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
              this.dataForm.money = 0
            })
        }
      })
    },
    handleProduct(row) {
      this.$confirm('此操作将生成会员卡' + row.title + ', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        productCard(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '制作会员卡成功'
            })
            row.cardUse = 1
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      }).catch(() => {
        return false
      })
    },

    handleDetail(row) {
      this.$router.push({ path: '/promotion/card_detail?cardId=' + row.id })
    },

    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      if (this.dataForm.days === 0 || this.dataForm.days == null) {
        this.dataForm.timeType = 1
      } else {
        this.dataForm.timeType = 0
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.dataForm.money = this.dataForm.money * 100
          updateCard(this.dataForm)
            .then(response => {
              this.getList()
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '创建卡成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    // 删除会员卡
    handleDelete(row) {
      this.$confirm('此操作将永久删除该会员卡' + row.title + ', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCard(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除会员卡成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      }).catch(() => {
        return false
      })
    },
    // 改变会员卡状态
    handleStatus(row) {
      // 如果会员卡已经过期
      if (row.status < 0) {
        this.$notify.error({
          title: '失败',
          message: '过期会员卡，建议删除'
        })
        return false
      }
      this.dataForm = Object.assign({}, row)
      this.dataForm.status = this.dataForm.status === 1 ? 0 : 1
      activeCard(this.dataForm)
        .then(response => {
          this.$notify.success({
            title: '成功',
            message: '修改会员卡成功'
          })
          // this.getList()
          row.cardUse = 1
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.data.errmsg
          })
        })
    },
    handleImport(row) {
      this.importDialogVisible = true
      this.importOptLoading = false
      this.$set(this, 'fileName', '')
      this.errList = []
      this.currentCardId = row.id
    },
    checkFile() {
      document.querySelector('#fileinput').click()
    },
    checkFileSure(val) {
      const file = document.querySelector('#fileinput').files[0]
      this.file = file
      this.fileName = file.name
    },
    importExcel() {
      this.errList = []
      this.importOptLoading = true
      importExcel(this.file, this.currentCardId)
        .then(response => {
          const result = response.data
          this.errList = response.data.failResult
          var type = result.errno === 200 ? 'success' : 'error'
          if (result && result.data && result.data !== '') {
            this.successResult = result.data.success
            this.errResult = result.data.fail
            this.allResult = result.data.total
            this.errList = (result.data.fail === 0 ? [] : result.data.failResult)
            this.innerImportDialogVisible = true
          } else {
            this.$notify({
              title: '成功',
              type: type,
              message: response.data.errmsg
            })
          }
          this.importOptLoading = false
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.data.errmsg
          })
          this.importOptLoading = false
          this.errList = []
        })
    },
    handleErrResult() {
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          '用户名',
          '手机号',
          '卡号',
          '卡名称',
          '金额',
          '失败原因'
        ]
        const filterVal = [
          'userName',
          'phone',
          'cardNo',
          'cardName',
          'money',
          'cause'
        ]
        excel.export_json_to_excel2(tHeader, this.errList, filterVal, '导入失败信息汇总')
      })
    },
    cardHandleExport() {
      exportUserCardToExcel()
    }
  }
}
</script>
